﻿// ===============================================================================
// XCI.Parent 西安交通信息WinForm开发框架 2019 版权所有
// ===============================================================================

using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using XCI.Core;
using XCI.Helper;
using XCI.Sys.Service;
using XCI.Windows;

namespace XCI.Sys.Forms
{
    public partial class FrmCaptcha : BaseForm
    {
        private readonly string _account;
        private bool isExit;
        private int count;

        public FrmCaptcha(string account)
        {
            InitializeComponent();
            _account = account;
        }

        /// <summary>
        /// 输入的验证码
        /// </summary>
        public string CaptchaCode { get;private set; }
        
        private async Task Build()
        {
            if (count > 10)
            {
                MessageBoxHelper.ShowError("请勿恶意刷新");
                return;
            }
            var bytes = await SysAccountService.Instance.CaptchaAsync(_account);
            if (bytes!=null)
            {
                var img = ImageHelper.FromArray(bytes);
                pictureBox1.Image = img;
                count++;
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Startup.Kill();
        }

        private async void FrmCaptcha_Load(object sender, EventArgs e)
        {
            await Build();
            editCaptcha.Width = pictureBox1.Width;
            this.TopMost = true;
        }

        private void FrmCaptcha_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = !isExit;
        }

        private void EditCaptcha_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == R.EnterKey)
            {
                btnValid.PerformClick();
            }
        }

        private async void PictureBox1_Click(object sender, EventArgs e)
        {
            await Build();
        }

        private void BtnValid_Click(object sender, EventArgs e)
        {
            CaptchaCode = editCaptcha.Text;
            if (string.IsNullOrEmpty(CaptchaCode))
            {
                MessageBoxHelper.ShowWarn("请输入验证码");
                editCaptcha.Select();
                return;
            }

            isExit = true;
            this.DialogResult = DialogResult.OK;
        }
    }
}